package com.glsc.ngateway.flowable.listener.demandmanagement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableDemandDto;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableDemand;
import com.glsc.ngateway.flowable.service.FlowableDemandService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DemandManagementConfirmHandler implements TaskListener, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DemandManagementConfirmHandler.class);


    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }


    @Override
    public void notify(DelegateTask delegateTask) {

        try {
            delegateTask.setVariable("reject", "0");

            FlowableDemandService flowableDemandService = (FlowableDemandService) applicationContext.getBean("flowableDemandService");
            String content = delegateTask.getVariable("content").toString();
            JSONObject json = JSONObject.parseObject(content);
            JSONObject demandSubmit = json.getJSONObject("demandSubmit");
            FlowableDemand demand = JSON.parseObject(demandSubmit.toJSONString(), FlowableDemand.class);
            List<FlowableDemandDto> exist = flowableDemandService.findByProcessInstanceId(delegateTask.getProcessInstanceId());
            FlowableDemandDto demandExist = exist.get(0);
            if (demandExist != null) {
                demandExist.setSolutionGeneral(demand.getSolutionGeneral());
                demandExist.setSolutionDocument(demand.getSolutionDocument());
                if (!StringUtils.isEmpty(demand.getDemandLevel())) {
                    demandExist.setDemandLevel(demand.getDemandLevel());
                }
                flowableDemandService.saveDemandSubmit(demandExist);
            }


        } catch (Exception e) {
            logger.error("DemandManagementConfirmHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
            throw new RuntimeException("DemandManagementConfirmHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
        }
    }

}